<template>
  <page-wrap stay-still back hide-tab title="附件简历预览">
    <view class="all">
      <!-- <view class="refresh">
        <u-icon name="error-circle-fill"></u-icon>
        资料更新后需要手动刷新生成新简历
        <span class="clickFresh" @click="createResume">点击刷新</span>
      </view> -->
      <!-- 排列三 -->
      <view class="attPicContainer">
        <u-image :src="attPic" mode="widthFix" show-error="more-dot-fill" @load="handleImageload"
          @error="handleImageError" @click="previewImg(attPic)"></u-image>
      </view>
      <view class="bottomSpace"></view>
      <view class="bottomBtn">
        <view class="optionBtn" @click="editResume"><img :src="editImg" />编辑简历</view>
        <view class="divider"></view>
        <view class="optionBtn" @click="changeWish"><img :src="changeImg" />更换样式</view>
        <view class="divider"></view>
        <view class="optionBtn" @click="showEmailInput = true"><img :src="exportImg" />导出</view>
        <view class="divider"></view>
        <view class="optionBtn" @click="handleSaveAtt"><img :src="saveImg" />保存到附件</view>
      </view>
    </view>

    <u-popup v-model="showWish" mode="bottom" height="90vh">
      <view class="chooseTemplate">
        <scroll-view :scroll-x="true" class="chooseTemplateContainer" scroll-with-animation enable-flex>
          <view v-for="item in templateList" :key="item.temId" @click.native="selectTemplate(item)">
            <view :class="{ 'selectedTemplate': (selectTemplateValue === item.temId) }">
              <image :src="item.temPic" class="img"></image>
              <view class="desc">{{ item.temName }} </view>
            </view>
          </view>
        </scroll-view>
        <view class="produce-btn">
          <view class="btn" @click="createResume">选择此模板</view>
        </view>
      </view>
    </u-popup>
    <!-- 下面是保存附件的弹窗 -->
    <u-popup v-model="showAttNameInput" mode="bottom">
      <view :class="{ 'popup-content': true, 'input-content': true, 'input-focus': attNameInputFocus }">
        <view class="input-container">
          <text>附件名字：</text>
          <input v-model="attName" type="text" placeholder="请输入附件名字" @focus="handleInputFocus" @blur="handleInputBlur">
        </view>
        <view class="button-container">
          <button class="cancel" @click="showAttNameInput = false">取消</button>
          <button @click="attNameConfirm">确定</button>
        </view>
      </view>
    </u-popup>
    <!-- 下面是导出到邮件的弹窗 -->
    <u-popup v-model="showEmailInput" mode="bottom">
      <view :class="{ 'popup-content': true, 'email': true, 'email-focus': emailInputFocus }">
        <view class="popup-title">
          导出简历模版至邮箱
          <img :src="closePopup" alt="" class="closePopup" @click="showEmailInput = false">
        </view>
        <img :src="exportToMailIcon" alt="" class="popup-image">
        <view class="input-container">
          <input v-model="emailAdress" type="text" placeholder="填写你的邮箱" @focus="handleInputFocus"
            @blur="handleInputBlur" @input="handleInput" maxlength="40">
          <button @click="emailConfirm" :class="{ 'email-confirm': true, 'hasInput': emailAdress }">确定发送</button>
        </view>
        <view class="validate-tip" v-show="!isEmailValidated && emailAdress">邮箱格式不正确，请检查后输入</view>
      </view>
    </u-popup>
    <!-- 顾问营销页面入口 -->
    <view class="resumeAssessmentEntrance" @click="toResumeAssessment">
      <view alt="" class="botIcon" />
      简历优化
      <img :src="resumeAssessmentEntranceIcon" alt="" class="resumeAssessmentEntranceIcon">
    </view>
    <!-- 预加载所有图片，防止序列帧闪动 -->
    <view class="preloadImages" style="display: none;">
      <!-- <image :src="`http://img3.job1001.com/ypMp/elan/images/resume/resultBotFrames/${n+1}_lq.png`" v-for="n in 19"
        :key="n+100" /> -->
    </view>
  </page-wrap>
</template>

<script>
// import html2canvas from 'html2canvas'
import { getMyIntendedTradeList } from "@/api/index";
import {
  createResumeAttachment,
  getPersonResumeAttachment,
  personSaveAttachment,
  getResumeTemplate,
} from "@/api/modules/resumeCreate";

import { addBuryingPoint } from "@/api/modules/career";
export default {
  data() {
    return {
      resumeAssessmentEntranceIcon:
        this.$imgBase + "resume/resumeAssessmentEntranceIcon.svg?v=1",
      exportToMailIcon: this.$imgBase + "resume/exportToMailIcon.png?v=1",
      selectTemplateValue: null,
      showEmailInput: false,
      attNameInputFocus: false,
      emailInputFocus: false,
      emailAdress: "",
      isEmailValidated: true,
      showAttNameInput: false,
      attName: "",
      attPic: "",
      id: "",
      closePopup: this.$imgBase + "resume/closePopup.svg?v=1",
      saveImg: this.$imgBase + "resume/resumeTemplateSave.svg?v=1",
      exportImg: this.$imgBase + "resume/resumeTemplateExport.svg?v=1",
      changeImg: this.$imgBase + "resume/resumeTemplateChange.svg?v=3",
      editImg: this.$imgBase + "resume/resumeTemplateEdit.svg?v=4",
      allAimList: [],
      showWish: false,
      personId: uni.getStorageSync("person-id").slice(2) || undefined,
      templateList: [
        {
          value: 1,
          url: this.$imgBase + "resume/template.png",
          desc: "通用蓝",
        },
        {
          value: 2,
          url: this.$imgBase + "resume/template.png",
          desc: "简约灰",
        },
        {
          value: 3,
          url: this.$imgBase + "resume/template.png",
          desc: "清爽",
        },
      ],
    };
  },
  onLoad(option) {
    console.log(option);
    this.id = option.id;
    this.attPic = decodeURIComponent(option.attPic);
    uni.showLoading({
      title: "简历拼命生成中~",
      mask: true,
    });
    console.log("this.attPic", this.attPic);
    this.getTemPlateList();
  },
  methods: {
    handleSaveAtt() {
      this.showAttNameInput = true;
      this.addBuryingPointFn(20003);
    },
    //普通的埋点
    async addBuryingPointFn(etId) {
      if (!this.personId) return;
      const params = {
        etId: etId,
        personId: uni.getStorageSync("person-id").slice(2) || "",
        cardType: this.cardType ? this.cardType : uni.getStorageSync("cardType") || this.cardType,
        consultantId: uni.getStorageSync("sellId")
          ? uni.getStorageSync("sellId")
          : "",
        // statType: this.statType ? this.statType : null,
        originType: this.originFrom == "shareLink" ? 10 : 20,
      };
      const res = await addBuryingPoint(params);
    },
    getTemPlateList() {
      const params = {
        personId: this.personId,
      };
      getResumeTemplate(params)
        .then((res) => {
          if (res.code == 200) {
            this.templateList = res.data;
          }
        })
        .catch((e) => {
          console.log(e);
        });
    },
    handleImageload() {
      uni.hideLoading();
    },
    handleImageError() {
      uni.hideLoading();
    },
    toResumeAssessment() {
      wx.reportEvent("resume_template_consultant_buy", {});
      this.addBuryingPointFn(20032);
      uni.navigateTo({
        url: "/pagesSub/userCenter/careerPathV2/components/CBuyPage?etId=20032",
      });
    },
    handleInput(e) {
      const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
      console.log("e", e.detail.value);
      this.isEmailValidated = emailRegex.test(e.detail.value);
      console.log("isEmailValidated", this.isEmailValidated);
    },
    handleInputBlur(e) {
      console.log("handleInputBlur", e);
      this.emailInputFocus = false;
      this.attNameInputFocus = false;
    },
    handleInputFocus(e) {
      console.log("handleInputFocus", e);
      this.$nextTick(() => {
        this.emailInputFocus = true;
        this.attNameInputFocus = true;
      });
    },
    selectTemplate(item) {
      this.selectTemplateValue = item.temId;
      console.log("selectTemplate", this.selectTemplateValue, item.temId);
    },
    emailConfirm() {
      // uni.navigateTo({
      //   url: `/pagesSub/newResume/resumeTemplate/resumeDetail/dentToEmail?id=${this.id}&ifSave=1`,
      // });
      if (!this.emailAdress) {
        uni.showToast({
          icon: "none",
          title: "请输入邮箱地址",
        });
        return;
      }
      if (!this.isEmailValidated) {
        uni.showToast({
          icon: "none",
          title: "邮箱格式不正确",
        });
        return;
      }
      uni.showLoading({
        title: "正在发送中",
        mask: true,
      });
      let param = {
        isSendEmail: 1,
        personId: uni.getStorageSync("person-id").slice(2) || undefined,
        attName: this.attName || "一览简历附件",
        id: this.id,
        email: this.emailAdress,
      };
      personSaveAttachment(param)
        .then((res) => {
          if (res.code == 200) {
            uni.showToast({
              icon: "none",
              title: "发送到邮箱并保存到附件成功",
            });
            this.addBuryingPointFn(20007);
            setTimeout(() => {
              this.showEmailInput = false;
            }, 1500);
          }
        })
        .finally(() => {
          uni.hideLoading();
          this.emailAdress = "";
        });
    },
    attNameConfirm() {
      if (!this.attName) {
        uni.showToast({
          icon: "none",
          title: "请输入附件名字",
        });
        return;
      }
      uni.showLoading({
        title: "正在保存到附件简历",
        mask: true,
      });
      let param = {
        isSendEmail: 2,
        personId: uni.getStorageSync("person-id").slice(2) || undefined,
        attName: this.attName,
        id: this.id,
      };
      personSaveAttachment(param)
        .then((res) => {
          if (res.code == 200) {
            uni.showToast({
              icon: "none",
              title: "保存成功！",
            });
            this.showAttNameInput = false;
            uni.navigateTo({
              url: `/pagesSub/newResume/resumeTemplate/resumeDetail/sendSuccess`,
            });
          } else {
            uni.showToast({
              icon: "none",
              title: res.status_desc || "保存失败！",
            });
          }
        })
        .catch(() => {
          uni.showToast({
            icon: "none",
            title: "保存失败！",
          });
        });
      uni.hideLoading();
    },
    previewImg(logourl) {
      let _this = this;
      let imgsArray = [];
      imgsArray[0] = logourl;
      uni.previewImage({
        current: 0,
        urls: imgsArray,
      });
    },
    createResume() {
      if (!this.selectTemplateValue) {
        uni.showToast({ icon: "none", title: "请先选择模板" });
        return;
      }

      const item = uni.getStorageSync("resumeTempalteSelectIntend");
      let param = {
        personId: this.personId,
        temId: this.selectTemplateValue,
        attName: "一览简历",
        attType: "1",
        attStatus: "2",
        intendedId: item.intended_id,
        intendName: item.zwname,
        salary: item.salary_str,
      };
      createResumeAttachment(param).then((res) => {
        if (+res.code === 200) {
          uni.showToast({ icon: "none", title: "简历提交成功" });
          uni.showLoading({
            title: "简历正在生成",
            mask: true,
          });
          this.showWish = false;
          this.startTime = new Date().getTime();
          this.getResumeTime();
        } else {
          uni.showToast({ icon: "none", title: res.status_desc });
        }
      });
    },

    getResumeTime() {
      clearTimeout(this.timer); // 清除定时器
      // 超过30分钟则停止轮询
      console.log(
        "new Date().getTime() - this.startTime > 30 * 1000",
        new Date().getTime() - this.startTime,
        30 * 1000 * 60
      );

      if (new Date().getTime() - this.startTime > 30 * 1000 * 60) {
        clearTimeout(this.timer);
        uni.showToast({ icon: "none", title: "服务器繁忙，请稍后重试" });
        return;
      }
      // 3s一次, 轮询中
      this.timer = setTimeout(() => {
        this.getResume(); // 调用轮询
      }, 2000);
    },
    getResume() {
      let param = {
        personId: this.personId,
        temId: this.selectTemplateValue,
      };
      getPersonResumeAttachment(param)
        .then((res) => {
          if (res && res.data.attPic) {
            console.log("成功了");
            uni.hideLoading();
            clearTimeout(this.timer);
            this.attPic = res.data.attPic;
            this.id = res.data.id;
          } else {
            clearTimeout(this.timer);
            // 没成功,调用轮询
            this.getResumeTime();
          }
        })
        .catch((err) => {
          // 请求错误,也继续轮询
          this.getResumeTime();
        });
    },
    changeWish() {
      this.showWish = true;
      // this.getMyIntendedTradeList();
    },
    getMyIntendedTradeList() {
      let param = {
        person_id: this.personId,
      };
      getMyIntendedTradeList(param).then((res) => {
        if (+res.code === 200) {
          this.allAimList = res.data.myTended || [];
        }
      });
    },
    editResume() {
      this.addBuryingPointFn(20004);
      //如果是新的简历页面来的就跳新的简历页面
      const pages = getCurrentPages();
      const prevPage = pages[pages.length - 2]; // 获取上一个页面的信息
      const prevPageRoute = prevPage ? prevPage.route : ""; // 获取上一个页面的路由
      if (prevPageRoute.indexOf("newResume") != -1) {
        uni.redirectTo({
          url: "/pagesSub/newResume/index",
        });
      } else {
        uni.redirectTo({
          url: `/pagesSub/newResume/index`,
        });
      }
    },
    save() {
      uni.navigateTo({
        url: `/pagesSub/resume/resumeTemplate/resumeDetail/dentToEmail?id=${this.id}&ifSave=1`,
      });
    },
  },
};
</script>
<style lang="scss" scoped>
$img-base-resume: $img-base + "resume/";

.all {
  position: relative;

  .refresh {
    width: 100%;
    display: flex;
    justify-content: center;
    height: 70rpx;
    align-items: center;

    .clickFresh {
      color: #d9001b;
      text-decoration: underline;
    }
  }

  .attPicContainer {
    padding: 32rpx;
    border-radius: 12rpx;
  }
}

.bottomSpace {
  height: 130rpx;
  width: 100%;
}

.bottomBtn {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100vw;
  height: 200rpx;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  padding-top: 48rpx;
  background-color: white;

  .optionBtn {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    flex: 1;
    color: #333;
    font-size: 24rpx;
  }

  .divider {
    width: 4rpx;
    height: 52rpx;
    border: 2rpx solid #e0e0e0;
    margin-top: 36rpx;
  }

  img {
    width: 52rpx;
    height: 56rpx;
    margin-bottom: 6rpx;
  }
}

.preview {
  position: relative;

  .wishContent {
    padding: 60rpx;
    min-height: 800rpx;

    .title {
      font-size: 22px;
      font-weight: 600;
    }

    .desc {
      color: #6b6b6b;
      margin: 20rpx 0;
    }

    .card {
      margin-bottom: 20rpx;
      box-shadow: 0px 5px 20px #e0dfdf;
      border-radius: 10rpx;
      display: flex;
      height: 200rpx;
      padding: 20rpx 20rpx 20rpx 34rpx;

      .cardRight {
        width: 220rpx;
        display: flex;
        align-items: center;
        justify-content: center;

        .chooseBtn {
          color: #fff;
          background: #f75a3e;
          border: none;
          width: 180rpx;
          height: 80rpx;
          line-height: 70rpx;
          font-size: 16px;
        }
      }

      .cardLeft {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: space-around;

        .cardLeft_title {
          font-size: 16px;
          font-weight: 900;
        }

        .cardLeft_money {
          font-size: 14px;
          color: #5f5d5d;
        }

        .cardLeft_type {
          font-size: 12px;
          color: #888;
        }
      }
    }
  }
}

.img {
  width: 200rpx;
  height: 300rpx;
  border: 2px solid #f75a3e;
}

.chooseTemplate {
  height: 38vh;
  padding: 44rpx 32rpx;
  position: relative;
  background: linear-gradient(180deg, #ffe7dc 0%, #ffffff 100%);
  border-radius: 28rpx 28rpx 0rpx 0rpx;

  .chooseTemplateContainer {
    height: 340rpx;
    display: flex;
    flex-wrap: nowrap;
    white-space: nowrap;
  }

  .selectedTemplate {
    .img {
      border: 4rpx solid #f75a3e;
    }
  }

  .img {
    width: 206rpx;
    height: 292rpx;
    box-shadow: 0rpx 4rpx 8rpx 0rpx rgba(255, 220, 200, 0.5);
    border-radius: 16rpx;
    border: 0;
    box-sizing: border-box;

    margin-right: 20rpx;
  }

  .desc {
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    font-size: 24rpx;
    color: #555555;
    line-height: 34rpx;
    text-align: center;
    font-style: normal;
    margin-top: 18rpx;
  }

  .produce-btn {
    width: calc(100vw - 64rpx);
    display: flex;
    justify-content: center;
    position: absolute;
    bottom: 0;
    // padding: 0 32rpx;
    padding-bottom: calc(2rpx + constant(safe-area-inset-bottom));
    padding-bottom: calc(2rpx + env(safe-area-inset-bottom));

    .btn {
      width: 100%;
      background: #f75a3e;
      color: #fff;
      font-size: 14px;
      height: 80rpx;
      line-height: 80rpx;
      margin-bottom: 20rpx;
    }
  }
}

.popup-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  height: 23vh;
  padding: 32rpx;

  &.input-content {
    height: 27vh;
  }

  &.input-focus {
    height: calc(27vh + 120rpx);
  }

  &.email {
    height: 40vh;
  }

  &.email-focus {
    height: calc(40vh + 90rpx);
    padding-bottom: 122rpx;
  }

  .popup-title {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-family: PingFang-SC, PingFang-SC;
    font-weight: 800;
    font-size: 40rpx;
    color: #000000;
    line-height: 56rpx;
    text-align: left;
    font-style: normal;

    .closePopup {
      width: 30rpx;
      height: 30rpx;
    }
  }

  .popup-image {
    width: 320rpx;
    height: 252rpx;
    margin-top: 32rpx;
    margin-bottom: 24rpx;
  }

  .input-container {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    margin-top: 40rpx;

    input {
      // width: 90%;
      flex: 1;
      height: 80rpx;
      outline: #f7743e;
      border: 2rpx solid #f7743e;
      border-radius: 10rpx;
      padding: 0 20rpx;
      font-size: 28rpx;
    }
  }

  .validate-tip {
    width: 100vw;
    padding: 0 40rpx;
    margin-top: 12rpx;
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    font-size: 26rpx;
    color: #e51616;
    line-height: 36rpx;
    text-align: left;
    font-style: normal;
  }

  .button-container {
    display: flex;
    justify-content: space-around;
    width: 100%;
    margin-top: 40rpx;

    button {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 80rpx;
      background: #f75a3e;
      color: #fff;
      font-size: 28rpx;
      border: none;
      border-radius: 10rpx;
      margin-right: 20rpx;

      &:last-of-type {
        margin-right: 0;
      }
    }

    .cancel {
      background: #b7b7b7;
    }
  }

  .email-confirm {
    display: flex;
    align-items: center;
    height: 80rpx;
    color: #fff;
    font-size: 28rpx;
    border: none;
    border-radius: 10rpx;
    margin-left: 16rpx;
    background-color: #ff9659;
    color: white;

    &.hasInput {
      background-color: #f7743e;
    }
  }
}

.desc {
  text-align: center;
  word-break: break-all;
  text-overflow: ellipsis;
  display: -webkit-box;
  color: #f75a3e;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  /* 这里是超出几行省略 */
  overflow: hidden;
  margin-bottom: 24rpx;
  width: 200rpx;
}

.resumeAssessmentEntrance {
  position: fixed;
  bottom: 228rpx;
  right: 0rpx;
  display: flex;
  align-items: center;
  // width: 240rpx;
  height: 64rpx;
  padding: 10rpx 14rpx;
  background: #ffffff;
  box-shadow: 0rpx 2rpx 18rpx 0rpx rgba(0, 0, 0, 0.15);
  border-radius: 200rpx 0rpx 0rpx 200rpx;
  font-family: PingFang-SC, PingFang-SC;
  font-weight: bold;
  font-size: 24rpx;
  color: #555555;
  line-height: 34rpx;
  text-align: left;
  font-style: normal;

  // @keyframes templateBotFramesSprites {
  //   0% {
  //     background-position: -10px -10px;
  //   }
  //   12% {
  //     background-position: -806px -10px; //第一个参数是网页里的最后一个数字 https://www.toptal.com/developers/css/sprite-generator
  //   }
  //   86% {
  //     background-position: -806px -10px; //保持静止
  //   }
  //   100% {
  //     background-position: -10px -10px;
  //   }
  // }
  // .botIcon {
  //   width: 44rpx;
  //   height: 44rpx;
  //   border-radius: 50%;
  //   margin-right: 12rpx;
  //   background-image: url($img-base-resume + "/templateBotFramesSprites.png"); /* 雪碧图路径 */
  //   // background-size: 82rpx 82rpx;
  //   background-position: -10px -10px;
  //   background-repeat: no-repeat;
  //   background-size: 840px auto;
  //   animation: templateBotFramesSprites 13s steps(19) forwards infinite;
  // }
  .botIcon {
    width: 44rpx;
    height: 44rpx;
    border-radius: 50%;
    margin-right: 12rpx;
    background-image: url($img-base + "/careerPath/consultant_entrance_hot.png");
    /* 雪碧图路径 */
    // background-size: 82rpx 82rpx;
    background-size: 100% 100%;
    // animation: templateBotFramesSprites 13s steps(19) forwards infinite;
  }

  .resumeAssessmentEntranceIcon {
    width: 18rpx;
    height: 18rpx;
    margin-left: 8rpx;
  }
}
</style>
